package com.developerstack.controller;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Base64;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.developerstack.model.User;

@Controller
public class UserController {

	@RequestMapping(path = "/user", method = RequestMethod.GET)
	public ResponseEntity<List<User>> listUser(HttpServletResponse response) {
		return new ResponseEntity<List<User>>(getUsers(), HttpStatus.OK);
	}

	@RequestMapping(path = "aws/user", method = RequestMethod.GET)
	public ResponseEntity<List<User>> listUseraws(HttpServletResponse response) {
		return new ResponseEntity<List<User>>(getUsers(), HttpStatus.OK);
	}

	// byte upload from camera
	@RequestMapping(value = "aws/uploadbytes", method = RequestMethod.POST)
	@ResponseBody
	public String uploadFilenewaws(@RequestParam("file") String str, HttpServletResponse response,
			HttpServletRequest request) throws Exception {
		String base64Image = str.split(",")[1];
		String typ = str.split(";")[0].split("/")[1];
		System.out.println("typ " + typ);
		byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);
		String origName = "imx_" + "xx_" + new Date().getTime() + "." + typ;
		String rawFileName = "/home/ubuntu/demo/" + origName;
		File file = new File(rawFileName);
		ImageIO.write(ImageIO.read(new ByteArrayInputStream(imageBytes)), typ, file);
		{
			String op = rawFileName.replace(origName, "modified_" + origName) + ".png";
			System.out.println(op);
			try {
				callPyLL(rawFileName, op);
				Thread.sleep(15000);
			} catch (Exception e) {
			}
			HttpHeaders headers = new HttpHeaders();
			FileSystemResource aa = new FileSystemResource(new File(op));
			InputStream in;
			byte[] media = null;
			try {
				in = aa.getInputStream();
				media = IOUtils.toByteArray(in);
			} catch (IOException e) {
			}
			headers.setCacheControl(CacheControl.noCache().getHeaderValue());

			byte[] encoded = Base64.getEncoder().encode(media);
			System.out.println(new String(encoded));
			return new String(encoded);
		}
		// return "success";
	}

	// byte upload from camera
	@RequestMapping(value = "/uploadbytes", method = RequestMethod.POST)
	@ResponseBody
	public String uploadFilenew(@RequestParam("file") String str, HttpServletResponse response,
			HttpServletRequest request) throws Exception {
		String base64Image = str.split(",")[1];
		String typ = str.split(";")[0].split("/")[1];
		System.out.println("typ " + typ);
		byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);
		String origName = "imx_" + "xx_" + new Date().getTime() + "." + typ;
		String rawFileName = "C:\\temp\\" + origName;
		File file = new File(rawFileName);
		ImageIO.write(ImageIO.read(new ByteArrayInputStream(imageBytes)), typ, file);
		{
			String op = rawFileName.replace(origName, "modified_" + origName) + ".png";
			System.out.println(op);
			try {
				callPy(rawFileName, op);
				Thread.sleep(15000);
			} catch (Exception e) {
			}
			HttpHeaders headers = new HttpHeaders();
			FileSystemResource aa = new FileSystemResource(new File(op));
			InputStream in;
			byte[] media = null;
			try {
				in = aa.getInputStream();
				media = IOUtils.toByteArray(in);
			} catch (IOException e) {
			}
			headers.setCacheControl(CacheControl.noCache().getHeaderValue());

			byte[] encoded = Base64.getEncoder().encode(media);
			System.out.println(new String(encoded));
			return new String(encoded);
		}
		// return "success";
	}

	// img upload from gallery
	@RequestMapping(value = "/uploadnew", method = RequestMethod.POST)
	@ResponseBody
	public String/* FileSystemResource */ uploadFilenew(/* @RequestParam("docId") String docId, */
			@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request)
			throws IOException {
		String docId = "xx";
		URI yahoo = null;
		try {
			yahoo = new URI("http://192.168.0.105:8100/#/home");
		} catch (URISyntaxException e) {
		}
		HttpHeaders httpHeaders = new HttpHeaders();
		httpHeaders.setLocation(yahoo);
		long ttime = new Date().getTime();
		String rawFileName = "C:\\temp\\" + docId + "_" + ttime + "_" + file.getOriginalFilename();
		FileCopyUtils.copy(file.getBytes(), new File(rawFileName));
		String op = rawFileName.replace(file.getOriginalFilename(), "modified_" + file.getOriginalFilename()) + ".png";
		try {
			callPy(rawFileName, op);
			Thread.sleep(15000);
		} catch (Exception e) {
		}
		// return op;
		/*
		 * return "http://localhost:5001/files/" + docId + "_" + ttime + "_" +
		 * "modified_" + file.getOriginalFilename() + ".png";
		 */
		HttpHeaders headers = new HttpHeaders();
		FileSystemResource aa = new FileSystemResource(new File(op));
		InputStream in;
		byte[] media = null;
		try {
			in = aa.getInputStream();
			media = IOUtils.toByteArray(in);
		} catch (IOException e) {
		}
		headers.setCacheControl(CacheControl.noCache().getHeaderValue());

		byte[] encoded = Base64.getEncoder().encode(media);
		System.out.println(new String(encoded));

		return new String(encoded);
	}

	// img upload from gallery
	@RequestMapping(value = "aws/uploadnew", method = RequestMethod.POST)
	@ResponseBody
	public String uploadFileAWSLL(@RequestParam("file") MultipartFile file, HttpServletResponse response,
			HttpServletRequest request) throws IOException {
		String docId = "xx";
		URI yahoo = null;
		try {
			yahoo = new URI("http://192.168.0.105:8100/#/home");
		} catch (URISyntaxException e) {
		}
		HttpHeaders httpHeaders = new HttpHeaders();
		httpHeaders.setLocation(yahoo);
		long ttime = new Date().getTime();
		String rawFileName = "/home/ubuntu/demo/" + docId + "_" + ttime + "_" + file.getOriginalFilename();
		FileCopyUtils.copy(file.getBytes(), new File(rawFileName));
		String op = rawFileName.replace(file.getOriginalFilename(), "modified_" + file.getOriginalFilename()) + ".png";
		try {
			callPyLL(rawFileName, op);
			Thread.sleep(15000);
		} catch (Exception e) {
		}
		// return op;
		/*
		 * return "http://13.127.158.136:5001/files/" + docId + "_" + ttime + "_" +
		 * "modified_" + file.getOriginalFilename() + ".png";
		 */
		HttpHeaders headers = new HttpHeaders();
		FileSystemResource aa = new FileSystemResource(new File(op));
		InputStream in;
		byte[] media = null;
		try {
			in = aa.getInputStream();
			media = IOUtils.toByteArray(in);
		} catch (IOException e) {
		}
		headers.setCacheControl(CacheControl.noCache().getHeaderValue());

		byte[] encoded = Base64.getEncoder().encode(media);
		System.out.println(new String(encoded));

		return new String(encoded);
	}

	/*
	 * @RequestMapping(value = "/upload", method = RequestMethod.POST)
	 * 
	 * @ResponseBody public String FileSystemResource
	 * uploadFile( @RequestParam("docId") String docId,
	 * 
	 * @RequestParam("file") MultipartFile file, HttpServletResponse response,
	 * HttpServletRequest request) throws IOException { String docId = "xx"; URI
	 * yahoo = null; try { yahoo = new URI("http://192.168.0.105:8100/#/home"); }
	 * catch (URISyntaxException e) { } HttpHeaders httpHeaders = new HttpHeaders();
	 * httpHeaders.setLocation(yahoo); long ttime = new Date().getTime(); String
	 * rawFileName = "C:\\temp\\" + docId + "_" + ttime + "_" +
	 * file.getOriginalFilename(); FileCopyUtils.copy(file.getBytes(), new
	 * File(rawFileName)); String op =
	 * rawFileName.replace(file.getOriginalFilename(), "modified_" +
	 * file.getOriginalFilename()) + ".png"; try { callPy(rawFileName, op);
	 * Thread.sleep(15000); } catch (Exception e) { } // return op; return
	 * "http://localhost:5001/files/" + docId + "_" + ttime + "_" + "modified_" +
	 * file.getOriginalFilename() + ".png"; }
	 */

	private void callPy(String rawFileName, String op) throws Exception {
		String command = "python C:\\FortyForty\\ssb\\demo_code_windows.py " + rawFileName
				+ " C:\\FortyForty\\ssb\\deeplabv3_mnv2_pascal_trainval_2018_01_29.tar.gz " + op;
		Process p = Runtime.getRuntime().exec(command);
	}

	//////////////////////////////////////
	/*
	 * @RequestMapping(value = "/uploadll", method = RequestMethod.POST)
	 * 
	 * @ResponseBody public String uploadFileLL(@RequestParam("file") MultipartFile
	 * file, HttpServletResponse response, HttpServletRequest request) throws
	 * IOException { String docId = "xx"; URI yahoo = null; try { yahoo = new
	 * URI("http://192.168.0.105:8100/#/home"); } catch (URISyntaxException e) { }
	 * HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setLocation(yahoo);
	 * long ttime = new Date().getTime(); String rawFileName = "/home/ubuntu/demo/"
	 * + docId + "_" + ttime + "_" + file.getOriginalFilename();
	 * FileCopyUtils.copy(file.getBytes(), new File(rawFileName)); String op =
	 * rawFileName.replace(file.getOriginalFilename(), "modified_" +
	 * file.getOriginalFilename()) + ".png"; try { callPyLL(rawFileName, op);
	 * Thread.sleep(15000); } catch (Exception e) { } // return op; return
	 * "http://13.127.158.136:5001/files/" + docId + "_" + ttime + "_" + "modified_"
	 * + file.getOriginalFilename() + ".png"; }
	 */

	private void callPyLL(String rawFileName, String op) throws Exception {
		String command = "python3 /home/ubuntu/demo/demo_code_linux.py " + rawFileName
				+ " /home/ubuntu/demo/deeplabv3_mnv2_pascal_trainval_2018_01_29.tar.gz " + op;
		System.out.println(command);
		Process p = Runtime.getRuntime().exec(command);
	}
	//////////////////////////////////////

	/*@RequestMapping(value = "/pdf", method = RequestMethod.POST)
	@ResponseBody
	public String getPDF(@RequestParam("pdffile") String str, HttpServletResponse response, HttpServletRequest request)
			throws Exception {
		return null;
	}*/

	//////////////////////////////////////

	/*
	 * @RequestMapping(value = "/image", method = RequestMethod.GET)
	 * public @ResponseBody String getImageAsResponseEntity() { HttpHeaders headers
	 * = new HttpHeaders(); FileSystemResource aa = new FileSystemResource(new
	 * File("C:\\FortyForty\\ssb\\op2.png")); InputStream in; byte[] media = null;
	 * try { in = aa.getInputStream(); media = IOUtils.toByteArray(in); } catch
	 * (IOException e) { }
	 * headers.setCacheControl(CacheControl.noCache().getHeaderValue());
	 * 
	 * byte[] encoded = Base64.getEncoder().encode(media); System.out.println(new
	 * String(encoded));
	 * 
	 * return new String(encoded); }
	 */

	private List<User> getUsers() {
		User user = new User();
		user.setId("12");
		user.setEmail("johndoe123@gmail.com");
		user.setName("John Doe");
		user.setAddress("Bangalore, Karnataka");
		User user1 = new User();
		user1.setId("13");
		user1.setEmail("amitsingh@yahoo.com");
		user1.setName("Amit Singh");
		user1.setAddress("Chennai, Tamilnadu");
		User user2 = new User();
		user2.setId("14");
		user2.setEmail("bipulkumar@gmail.com");
		user2.setName("Bipul Kumar");
		user2.setAddress("Bangalore, Karnataka");
		User user3 = new User();
		user3.setId("15");
		user3.setEmail("prakashranjan@gmail.com");
		user3.setName("Prakash Ranjan");
		user3.setAddress("Chennai, Tamilnadu");
		return Arrays.asList(user, user1, user2, user3, user1, user2, user1, user2, user1, user2, user1, user2, user1, user2, user1, user2, user1, user2);
	}

}